package io.renren.modules.work.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import io.renren.common.utils.ConfigConstant;
import io.renren.common.utils.R;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.work.dao.ScProjectdtlDao;
import io.renren.modules.work.entity.ScConsumablesEntity;
import io.renren.modules.work.entity.ScProjectEntity;
import io.renren.modules.work.entity.ScProjectdtlEntity;
import io.renren.modules.work.service.ScConsumablesService;
import io.renren.modules.work.service.ScProjectService;
import io.renren.modules.work.service.ScProjectdtlService;
import io.renren.vo.ScConsumablesVo;
import io.renren.vo.ScProjectEntityVo;
import io.renren.vo.ScProjectdtlVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import org.springframework.transaction.annotation.Transactional;


@Service("scProjectdtlService")
@Slf4j
public class ScProjectdtlServiceImpl extends ServiceImpl<ScProjectdtlDao, ScProjectdtlEntity> implements ScProjectdtlService {


    @Autowired
    private ScConsumablesService scConsumablesService;
    @Autowired
    private ScProjectdtlService scProjectdtlService;

    @Autowired
    private ScProjectService scProjectService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //时间判断
        String sTime = null;
        String eTime = null;
        if(StringUtils.isNotBlank((String) params.get("sTime"))&&StringUtils.isNotBlank((String) params.get("eTime"))){
            sTime = sdf.format( Long.parseLong((String) params.get("sTime")));
            eTime = sdf.format( Long.parseLong((String) params.get("eTime")));
        }

        IPage<ScProjectdtlVo> page = baseMapper.selectProjectDtlVo(new Query<ScProjectdtlVo>().getPage(params)
                , (String) params.get("projectdtlname"),
                (String) params.get("projectid"),
                (String) params.get("cretimeSort"),
                (String) params.get("priceSort"),
                sTime,
                eTime);

        return new PageUtils(page);
    }

    @Override
    public ScProjectdtlEntity saveProjectDtl(ScProjectdtlEntity scProjectdtlEntity) {
        baseMapper.insert(scProjectdtlEntity);
        return scProjectdtlEntity;
    }

    @Override
    public R updateProjectdtl(String params) {

        log.info("调用更新子工程接口");
        log.info("{}:",params);
        ScProjectdtlVo scProjectdtlVo = JSONObject.parseObject(params, ScProjectdtlVo.class);

        //更新子工程
        QueryWrapper<ScProjectdtlEntity> scProjectEntityQueryWrapper = new QueryWrapper<>();
        scProjectEntityQueryWrapper.eq("projectdtlid",scProjectdtlVo.getProjectdtlid());

        ScProjectdtlEntity scProjectdtlEntity = baseMapper.selectOne(scProjectEntityQueryWrapper);
        //判断是否处于同个月份，不一致的话泽无法修改数据
        Date cretime = scProjectdtlEntity.getCretime();
        int month = cretime.getMonth();
        Date now = new Date();
        int nowMonth = now.getMonth();
        if(month!=nowMonth){
          //  return R.error("该单据是"+month+1+"月份的，无法再进行修改");
        }

        //判断主工程是否为初始状态
        ScProjectEntity scproject = scProjectService.getById(scProjectdtlEntity.getProjectid());
        if(!scproject.getProjectStatus().equals(ConfigConstant.PROJETCT_INITIAL)){
            return R.error("该工程不是初始状态，无法修改");
        }
        scProjectdtlEntity.setProjectdtlname(scProjectdtlVo.getProjectdtlname());
        scProjectdtlEntity.setHandleState(scProjectdtlVo.getHandleState());
        scProjectdtlEntity.setQualityState(scProjectdtlVo.getQualityState());
        scProjectdtlEntity.setWorkhours(scProjectdtlVo.getWorkhours());
        scProjectdtlEntity.setManhourfee(scProjectdtlVo.getManhourfee());
        scProjectdtlEntity.setMaterialcost(scProjectdtlVo.getMaterialcost());
        scProjectdtlEntity.setSpecialfee(scProjectdtlVo.getSpecialfee());
        scProjectdtlEntity.setOutsourcingFee(scProjectdtlVo.getOutsourcingFee());
        scProjectdtlEntity.setOthercost(scProjectdtlVo.getOthercost());
        scProjectdtlEntity.setMemo(scProjectdtlVo.getMemo());
        scProjectdtlEntity.setSafe(scProjectdtlVo.getSafe());
        scProjectdtlEntity.setSkill(scProjectdtlVo.getSkill());
        scProjectdtlEntity.setBrokenstatus(scProjectdtlVo.getBrokenstatus());
        scProjectdtlEntity.setBillno(scProjectdtlVo.getBillno());
        scProjectdtlEntity.setPurno(scProjectdtlVo.getPurno());
        baseMapper.updateById(scProjectdtlEntity);


        //更新器材
        List<ScConsumablesVo> scConsumables = scProjectdtlVo.getScConsumables();
        //过滤出已存在的器材
        List<ScConsumablesVo> collect = scConsumables.stream().filter(p -> StringUtils.isNotBlank(p.getConsumablesid())).collect(Collectors.toList());
        QueryWrapper<ScConsumablesEntity> scConsumablesEntityQueryWrapper = new QueryWrapper<>();
        List<String> ids = new ArrayList<>();
        for (ScConsumablesVo scConsumablesVo : collect) {
            ids.add(scConsumablesVo.getConsumablesid());
        }

        scConsumablesEntityQueryWrapper.eq("projectdtlid",scProjectdtlVo.getProjectdtlid());
        if (ids.size()>0){
            scConsumablesEntityQueryWrapper.notIn("consumablesid",ids);
        }
        //删除未提交的器材
        scConsumablesService.remove(scConsumablesEntityQueryWrapper);

        for (ScConsumablesVo scConsumable : scConsumables) {
            ScConsumablesEntity scConsumablesEntity = new ScConsumablesEntity();
            BeanUtil.copyProperties(scConsumable,scConsumablesEntity);
            BigDecimal pamount = scConsumable.getPamount();
            scConsumablesEntity.setPrice(pamount);
            scConsumablesEntity.setIfstore(1);
            if(!scConsumable.getIfstore()){
                scConsumablesEntity.setGoodsid(null);
            }
            if(StringUtils.isNotBlank(scConsumable.getConsumablesid())){
                scConsumablesService.updateById(scConsumablesEntity);
            }else{
                scConsumablesEntity.setProjectid(scProjectdtlEntity.getProjectid());
                scConsumablesEntity.setProjectdtlid(scProjectdtlEntity.getProjectdtlid());
                scConsumablesService.save(scConsumablesEntity);
            }
        }

        caculatePrice(scProjectdtlEntity.getProjectid());
        log.info("更新工程金额完成");
        log.info("更新工程完成");
        return R.ok();
    }

    @Override
    @Transactional
    public R commitProject(String params, SysUserEntity user) {
        log.info("调用保存子工程接口");
        log.info("{}:",params);
        //工程id
        String dtlId = ConfigConstant.getId();

        ScProjectdtlVo scProjectdtlVo = JSONObject.parseObject(params, ScProjectdtlVo.class);
        //保存子工程
        ScProjectdtlEntity scProjectdtlEntity = new ScProjectdtlEntity();
        scProjectdtlEntity.setProjectdtlid(dtlId);
        scProjectdtlEntity.setProjectdtlno(dtlId);
        scProjectdtlEntity.setProjectdtlname(scProjectdtlVo.getProjectdtlname());
        scProjectdtlEntity.setHandleState(scProjectdtlVo.getHandleState());
        scProjectdtlEntity.setQualityState(scProjectdtlVo.getQualityState());
        scProjectdtlEntity.setWorkhours(scProjectdtlVo.getWorkhours());
        scProjectdtlEntity.setManhourfee(scProjectdtlVo.getManhourfee());
        scProjectdtlEntity.setMaterialcost(scProjectdtlVo.getMaterialcost());
        scProjectdtlEntity.setSpecialfee(scProjectdtlVo.getSpecialfee());
        scProjectdtlEntity.setOutsourcingFee(scProjectdtlVo.getOutsourcingFee());
        scProjectdtlEntity.setOthercost(scProjectdtlVo.getOthercost());
        scProjectdtlEntity.setMemo(scProjectdtlVo.getMemo());
        scProjectdtlEntity.setProjectid(scProjectdtlVo.getProjectid());
        scProjectdtlEntity.setCreman(user.getUsername());
        scProjectdtlEntity.setCremanid(Integer.parseInt(user.getUserId().toString()));
        scProjectdtlEntity.setBrokenstatus(scProjectdtlVo.getBrokenstatus());
        scProjectdtlEntity.setSafe(scProjectdtlVo.getSafe());
        scProjectdtlEntity.setSkill(scProjectdtlVo.getSkill());
        scProjectdtlEntity.setPrice(scProjectdtlVo.getPrice());
        scProjectdtlEntity.setPurno(scProjectdtlVo.getPurno());
        scProjectdtlService.save(scProjectdtlEntity);
        //保存器材
        List<ScConsumablesVo> scConsumables = scProjectdtlVo.getScConsumables();

        if(scConsumables!=null){
            for (ScConsumablesVo scConsumable : scConsumables) {
                if(StringUtils.isBlank(scConsumable.getGoodsid())&&scConsumable.getIfstore()){
                    continue;
                }
                ScConsumablesEntity scConsumablesEntity = new ScConsumablesEntity();
                scConsumablesEntity.setProjectdtlid(dtlId);
                scConsumablesEntity.setProjectid(scProjectdtlVo.getProjectid());
                scConsumablesEntity.setGoodsid(scConsumable.getGoodsid());
                scConsumablesEntity.setGoodsname(scConsumable.getGoodsname());
                scConsumablesEntity.setSingleprice(scConsumable.getSingleprice());
                scConsumablesEntity.setGoodsunit(scConsumable.getGoodsunit());
                scConsumablesEntity.setGoodstype(scConsumable.getGoodstype());
                scConsumablesEntity.setNum(scConsumable.getNum());
                scConsumablesEntity.setPrice(scConsumable.getPamount()==null?new BigDecimal("0"):scConsumable.getPamount());
                scConsumablesEntity.setIfstore(scConsumable.getIfstore() ?1:0);
                if(!scConsumable.getIfstore()){
                    scConsumablesEntity.setGoodsid(null);
                }
                scConsumablesService.save(scConsumablesEntity);
            }
        }


        log.info("保存子工程完成");
        caculatePrice(scProjectdtlVo.getProjectid());
        log.info("更新工程金额完成");


        return R.ok();
    }

    @Override
    @Transactional
    public void caculatePrice(String projectid) {
        ScProjectEntity scProjectEntity = scProjectService.getById(projectid);
        QueryWrapper<ScProjectdtlEntity> projectdtlEntityQueryWrapper = new QueryWrapper<>();
        projectdtlEntityQueryWrapper.eq("projectid",scProjectEntity.getProjectid());
        List<ScProjectdtlEntity> list = scProjectdtlService.list(projectdtlEntityQueryWrapper);
        //总工程费用
        BigDecimal finalPrice = new BigDecimal(0);
        for (ScProjectdtlEntity scProjectdtlEntity : list) {
            //工时
            BigDecimal workHour = scProjectdtlEntity.getWorkhours()==null? new BigDecimal("0"):scProjectdtlEntity.getWorkhours();
            //工时费
            BigDecimal manHourFee = scProjectdtlEntity.getManhourfee()==null? new BigDecimal("0"):scProjectdtlEntity.getManhourfee();
            //工价
            BigDecimal workFee = workHour.multiply(manHourFee);
            //材料费（手填）
            BigDecimal materialcost = scProjectdtlEntity.getMaterialcost()==null?new BigDecimal("0"):scProjectdtlEntity.getMaterialcost();
            //材料费(自动计算)
            BigDecimal materialcost4cal = new BigDecimal("0");
            QueryWrapper<ScConsumablesEntity> scConsumablesEntityQueryWrapper = new QueryWrapper<>();
            scConsumablesEntityQueryWrapper.eq("projectdtlid",scProjectdtlEntity.getProjectdtlid());
            List<ScConsumablesEntity> goodsList = scConsumablesService.list(scConsumablesEntityQueryWrapper);
            for (ScConsumablesEntity scConsumablesEntity : goodsList) {
                materialcost4cal = materialcost4cal.add(scConsumablesEntity.getPrice());
            }

            //专项费用
            BigDecimal specialFee = scProjectdtlEntity.getSpecialfee()==null? new BigDecimal("0"):scProjectdtlEntity.getSpecialfee();
            //其它费用
            BigDecimal othercost = scProjectdtlEntity.getOthercost()== null ? new BigDecimal("0") : scProjectdtlEntity.getOthercost();
            //外协费用
            BigDecimal outsourcingFee = scProjectdtlEntity.getOutsourcingFee() == null ? new BigDecimal("0") : scProjectdtlEntity.getOutsourcingFee();
            //子工程总费用
            BigDecimal price = workFee.add(materialcost).add(specialFee).add(othercost).add(outsourcingFee);
            scProjectdtlEntity.setMaterialcost4cal(materialcost4cal);
            scProjectdtlEntity.setPrice(price);
            scProjectdtlService.updateById(scProjectdtlEntity);
            finalPrice = finalPrice.add(price);
        }
        scProjectEntity.setTotalprice(finalPrice);
        scProjectService.updateById(scProjectEntity);
    }

}